<template>
  <div class="page">
    <BrandHeader />
    <div class="content">
      <!-- 左侧：播放器 + 详情 -->
      <div class="left">
        <!-- 顶部返回行 -->
        <div class="topbar">
          <button class="back-btn" @click="goBack" aria-label="返回上一页">返回</button>
        </div>
        <!-- 标题行 -->
        <div class="page-title" v-if="detail">
          <h1 class="title">{{ detail.title || '未命名电影' }}</h1>
        </div>
        <div class="player-card">
          <video
            ref="videoEl"
            class="video"
            :src="streamUrl"
            controls
            autoplay
            playsinline
          />
        </div>
        <div class="detail-card" v-if="detail">
          <div class="meta-line">
            <span v-if="detail.year" class="year">{{ detail.year }}</span>
            <div class="meta" v-if="parsedGenres.length">
              <span class="tag" v-for="g in parsedGenres" :key="g">{{ g }}</span>
            </div>
          </div>
          <p class="overview" v-if="detail.overview">{{ detail.overview }}</p>
        </div>
      </div>

      <!-- 右侧：相似推荐 -->
      <aside class="right">
        <h2 class="section-title">相似推荐</h2>
        <div class="reco-list">
          <div
            class="reco-item"
            v-for="m in similar"
            :key="m.id"
            @click="goDetail(m.id)"
          >
            <div class="poster" :style="bgImage(m.poster)"></div>
            <div class="info">
              <div class="name" :title="m.title">{{ m.title }}</div>
              <div class="sub">
                {{ m.year || '' }}
                <template v-if="toArr(m.genres).length">
                  <span class="sep">·</span>
                  <span class="genres-inline">
                    <span class="g-inline" v-for="g in toArr(m.genres).slice(0,3)" :key="g">{{ g }}</span>
                  </span>
                </template>
              </div>
            </div>
          </div>
        </div>
      </aside>
    </div>
  </div>
  
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getMovieDetail, getSimilarMovies, getStreamUrl } from '@/services/api'
import BrandHeader from '@/components/BrandHeader.vue'

const route = useRoute()
const router = useRouter()
const movieId = computed(() => Number(route.params.id))

const detail = ref(null)
const similar = ref([])
const streamUrl = computed(() => getStreamUrl(movieId.value))

const parsedGenres = computed(() => {
  if (!detail.value?.genres) return []
  if (Array.isArray(detail.value.genres)) return detail.value.genres
  return String(detail.value.genres).split('|').filter(Boolean).slice(0, 6)
})

function bgImage(url) {
  return url ? { backgroundImage: `url(${url})` } : {}
}

function toArr(genres) {
  if (!genres) return []
  return Array.isArray(genres) ? genres : String(genres).split('|').filter(Boolean)
}

// 归一化相似电影条目，确保有 id 与 genres 字段
function normalizeMovie(m) {
  const genres = m?.genres ?? m?.genre ?? m?.genre_names ?? m?.genreNames ?? m?.genres_str ?? ''
  return {
    ...m,
    id: m?.id ?? m?.movieId,
    genres,
  }
}

async function load() {
  if (!movieId.value) return
  // 详情
  try {
    const res = await getMovieDetail(movieId.value)
    detail.value = res.data
  } catch (e) {
    // 忽略错误（详情可能缺失）
    // eslint-disable-next-line no-unused-vars
    const _ignore = e
  }
  // 相似
  try {
    const res2 = await getSimilarMovies(movieId.value, 5)
    const base = (res2.data || []).slice(0,5).map(normalizeMovie)
    similar.value = await enrichSimilar(base)
  } catch (e) {
    // 忽略错误并置空列表
    similar.value = []
  }
}
// 若缺少类型或年份，调用详情接口补全
async function enrichSimilar(items) {
  return Promise.all(items.map(async (m) => {
    if (toArr(m.genres).length > 0 && m.year) return m
    try {
      const d = await getMovieDetail(m.id)
      const data = d?.data || {}
      return {
        ...m,
        year: m.year || data.year,
        genres: toArr(m.genres).length ? m.genres : (data.genres || m.genres)
      }
    } catch (e) {
      return m
    }
  }))
}

function goDetail(id) {
  if (!id) return
  router.push({ name: 'movie', params: { id } })
}

function goBack() {
  // 优先返回上一页，否则回首页
  if (window.history.length > 1) router.back()
  else router.push('/recommend')
}

onMounted(load)
watch(() => route.params.id, load)
</script>

<style scoped>
/* 页面基底 */
.page { min-height: 100vh; background: #0f0f0f; }
.content { width: 100%; margin: 0; display: grid; grid-template-columns: minmax(0,1fr) 380px; gap: 12px; padding: 8px; box-sizing: border-box; }

/* 顶部与返回按钮 */
.topbar { margin-bottom: 8px; }
.back-btn {
  background: #fff;
  color: #000;
  border: 1px solid #e5e5e5;
  border-radius: 10px;
  padding: 8px 14px;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: background .15s ease, transform .1s ease;
}
.back-btn:hover { background: #f2f2f2; transform: translateY(-1px); }
.back-btn:focus-visible { outline: 2px solid #000; outline-offset: 2px; }
.page-title { margin: 4px 0 10px; }

/* 左侧 */
.left { min-width: 0; display:flex; flex-direction: column; }
.player-card { background: #000; border-radius: 10px; overflow: hidden; box-shadow: 0 10px 30px rgba(0,0,0,.5); aspect-ratio: 3 / 2; }
.video { width: 100%; height: 100%; display: block; background: #000; object-fit: cover; }
.player-topbar { display:flex; align-items: center; justify-content: flex-start; gap: 8px; padding: 8px; background: #0d0d0d; border-bottom: 1px solid #1a1a1a; }
.tabs { display:flex; gap: 8px; }
.tab { background: #1a1a1a; color:#eee; border: 1px solid #2a2a2a; padding: 6px 10px; border-radius: 8px; cursor: pointer; font-size: 13px; }
.tab.active { background: #ff4e4e; border-color: #ff4e4e; color: #fff; }
.tab:disabled { opacity: .5; cursor: not-allowed; }
.detail-card { margin-top: 12px; background: #121212; border-radius: 10px; padding: 14px 16px; color: #eee; box-shadow: 0 6px 18px rgba(0,0,0,.35); }
.title-line { display:flex; align-items: baseline; gap: 10px; }
.title { font-size: 22px; font-weight: 700; margin: 0; color: #fff; }
.year { color: #9aa0a6; font-size: 14px; }
.meta-line { display:flex; align-items: center; gap: 10px; }
.meta { margin-top: 8px; display:flex; flex-wrap: wrap; gap: 8px; }
.tag { background: #1f1f1f; color:#bdbdbd; padding: 4px 10px; border-radius: 999px; font-size: 12px; }
.overview { margin-top: 12px; line-height: 1.7; color: #cfd2d4; }

/* 右侧 */
.right { color:#ddd; height: 100%; display:flex; flex-direction: column; }
.section-title { font-size: 18px; margin: 0 0 10px; color:#fafafa; }
.reco-list { display:flex; flex-direction: column; gap: 10px; overflow: auto; padding-right: 4px; flex: 1; }
.reco-item { display:flex; gap: 12px; background: #121212; border-radius: 10px; padding: 8px; cursor: pointer; transition: transform .15s ease, background .15s ease; }
.reco-item:hover { transform: translateY(-2px); background: #181818; }
.poster { width: 140px; height: 190px; background:#222 center/cover no-repeat; border-radius: 8px; flex: none; }
.info { min-width: 0; display:flex; flex-direction: column; justify-content: center; }
.name { color:#fff; font-weight: 600; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }
.sub { color:#9aa0a6; font-size: 12px; margin-top: 6px; white-space: normal; overflow: visible; }
.sub .sep { margin: 0 6px; color:#6b7280; }
.genres-inline { display: inline-flex; gap: 6px; vertical-align: middle; flex-wrap: wrap; }
.g-inline { background: #1f1f1f; color:#bdbdbd; padding: 2px 6px; border-radius: 999px; font-size: 11px; }
.genres { margin-top: 6px; display:flex; align-items: center; gap: 8px; }
.genres .label { color:#bdbdbd; font-size: 12px; background: #1a1a1a; border: 1px solid #262626; padding: 2px 6px; border-radius: 6px; }
.g-tags { margin-top: 6px; display:flex; flex-wrap: wrap; gap: 6px; }
.g-tag { background: #1f1f1f; color:#bdbdbd; padding: 2px 8px; border-radius: 999px; font-size: 11px; }

/* 响应式 */
@media (max-width: 1024px) {
  .content { grid-template-columns: 1fr; }
  .right { order: -1; height: auto; }
  .left { height: auto; }
  .player-card { aspect-ratio: 3 / 2; }
}
</style>